#include "../StdInc.h"

namespace GSTrader
{
	namespace Indicator
	{
		WMA::WMA()
		{
			m_strIndicatorName = "WMA";
			m_nLength = 0;
			m_nBarType = bdtClose;
		}


		WMA::~WMA()
		{
		}

		CIndicator* WMA::CreateInstance()
		{
			return new WMA;
		}

		void WMA::SetParam(int nLength, int nBarType)
		{
			m_nLength = nLength;
			m_nBarType = nBarType;

			RefreshData();
		}

		void WMA::SetParam(double* pdParam)
		{
			if (pdParam == NULL)
			{
				return;
			}

			m_nLength = (int)pdParam[0];
			m_nBarType = (int)pdParam[1];

			RefreshData();
		}

		double WMA::Calculate(int nIndex)
		{
			if (m_pInput == NULL || m_pInput->m_nStartIndex < 0 || m_nLength <= 0)
				return 0;

			int nCount = m_pInput->GetCount();
			int nStartIndex = nIndex - m_nLength + 1;
			if (nStartIndex < 0 || nIndex >= nCount)
				return 0;

			int nNum = m_nLength / 2 * (m_nLength + 1);

			double dSum = 0, dValue;
			for (int j = 0; j < m_nLength; j++)
			{
				dValue = m_pInput->GetValue(nIndex - j, m_nBarType);
				dSum += (dValue * (m_nLength - j));
			}

			dValue = dSum / nNum;
			m_pResult->SetValue(nIndex, dValue);

			return dValue;
		}

		void WMA::RefreshData()
		{
			if (m_pInput == NULL || m_pInput->m_nStartIndex < 0 || m_nLength <= 0 )
			{
				m_pResult->m_pDataSeries->m_nStartIndex = -1;
				return;
			}

			int nCount = m_pInput->GetCount();
			int nStartIndex = m_pInput->m_nStartIndex + m_nLength - 1;
			m_pResult->m_pDataSeries->SetSize(nCount, nStartIndex);

			m_bCalc = true;
		}
	}
}
